package com.example.aidlclient;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.aidlserver.Book;
import com.example.aidlserver.BookController;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Client";

    private BookController bookController;
    private boolean connected;

    private List<Book> bookList;

    private ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bookController=BookController.Stub.asInterface(service);
            connected=true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            connected=false;
        }
    };

    private View.OnClickListener clickListener= v -> {
        if (v.getId()==R.id.btn_getBookList){
            if (connected){
                try {
                    bookList=  bookController.getBookList();
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
                log();
            }
        }else if (v.getId()==R.id.btn_addBook_inOut){
            if (connected){
                Book book = new Book("这是一本新书 InOut");
                try {
                    bookController.addBookInOut(book);
                    Log.e(TAG, "向服务器以InOut方式添加了一本新书");
                    Log.e(TAG, "新书名：" + book.getName());
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button getBtn = findViewById(R.id.btn_getBookList);
        Button addBtn = findViewById(R.id.btn_addBook_inOut);

        getBtn.setOnClickListener(clickListener);
        addBtn.setOnClickListener(clickListener);

        bindService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connected){
            unbindService(serviceConnection);
        }
    }

    private void bindService() {
        Intent intent=new Intent();
        intent.setPackage("com.example.aidlserver");
        intent.setAction("com.example.aidlserver.action");
        bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void log(){
        for (Book book:bookList){
            Log.e(TAG, book.toString() );
        }
    }
}